import { spawn } from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';
import { starlight } from '../config';
import type { Definitions } from '../../starlight/user-components/rehype-file-tree';

const copyrightNotice = `/**
* Based on https://github.com/elviswolcott/seti-icons which
* is derived from https://github.com/jesseweed/seti-ui/
*
* Copyright (c) 2014 Jesse Weed
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/`;

const generatedFileHeader = `/**
* This file was generated by the \`file-icons-generator\` package.
* Do not edit this file directly as it will be overwritten.
*/`;

/** Write the generated definitions and SVGs to the Starlight package. */
export async function writeDefinitionsAndSVGs(
	definitions: Definitions,
	svgPaths: Record<string, string>
) {
	const content = `${generatedFileHeader}

import type { Definitions } from './rehype-file-tree.ts';

${copyrightNotice}
export const definitions: Definitions = ${JSON.stringify(definitions)};

export const FileIcons = ${JSON.stringify(svgPaths)};
`;

	const filePath = path.join('..', 'starlight', starlight.output);

	await fs.writeFile(filePath, content);

	await prettifyFile(path.resolve(filePath));
}

/** Run Prettier on a generated file. */
function prettifyFile(filePath: string) {
	return new Promise<void>((resolve, reject) => {
		const child = spawn('pnpm', ['prettier', '-w', filePath], {
			cwd: '../..',
			stdio: [],
		});

		const error = new Error('Failed to run Prettier on the generated file.');

		child.on('error', () => reject(error));
		child.on('close', (code) => {
			if (code !== 0) {
				reject(error);

				return;
			}

			resolve();
		});
	});
}
